package com.example.administrator.zhongyichou.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.zhongyichou.Bean.BaseEventBean;
import com.example.administrator.zhongyichou.Bean.ChoiceBean;
import com.example.administrator.zhongyichou.adapter.LaunchDiseaseGridAdapter;
import com.example.administrator.zhongyichou.base.BaseActivity;
import com.example.administrator.zhongyichou.base.MyApplication;
import com.example.administrator.zhongyichou.config.Constants;
import com.example.administrator.zhongyichou.net.NetConfig;
import com.example.administrator.zhongyichou.net.core.RequestHttpLoader;
import com.example.administrator.zhongyichou.net.core.UploadHttpLoader;
import com.example.administrator.zhongyichou.net.presentor.BankTypeProtocol;
import com.example.administrator.zhongyichou.net.protocol.GsonBaseProtocol;
import com.example.administrator.zhongyichou.net.protocol.LaunchDreamProtocol;
import com.example.administrator.zhongyichou.utils.FileUtils;
import com.example.administrator.zhongyichou.utils.ImageUtils;
import com.example.administrator.zhongyichou.utils.ToastUtil;
import com.example.administrator.zhongyichou.view.ChoiceDialog;
import com.example.administrator.zhongyichou.view.LoadingDialog;
import com.example.administrator.zhongyichou.view.MyGridView;
import com.example.administrator.zhongyichou.net.core.HttpLoader;
import com.example.administrator.zhongyichou.net.listener.ResultListener;
import com.example.administrator.zhongyichou.view.HeaderView;
import com.example.administrator.zhongyichou.R;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.preview.ImagePreviewActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.nereo.multi_image_selector.MultiImageSelector;

/**
 * Created by lichenyu on 2017/11/21.
 * 描述： 补充梦想资料
 */

public class DreamDataActivity extends BaseActivity implements AdapterView.OnItemClickListener, LaunchDiseaseGridAdapter.OnClickListener, ChoiceDialog.OnClik {
    @BindView(R.id.headerview)
    HeaderView headerview;
    @BindView(R.id.ll_choose_prove)
    LinearLayout llChooseProve;
    @BindView(R.id.gridview)
    MyGridView gridview;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_id)
    EditText editId;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.txt_bank)
    TextView txtBank;
    @BindView(R.id.edit_card_id)
    EditText editCardId;
    private int REQUEST_IMAGE = 10;
    private ArrayList<String> listPhoto = new ArrayList<>();
    private LaunchDiseaseGridAdapter adapter;
    private BankTypeProtocol bankTypeProtocol;
    private String bankType = "-1";
    private ChoiceDialog choiceDialog;
    private LoadingDialog dialog;
    private String infoID;
    private String name;
    private String id;
    private String phone;
    private String bankNum;

    @Override
    protected void init() {
        ButterKnife.bind(this);
        initHead();
        initDialog();
        adapter = new LaunchDiseaseGridAdapter(this, listPhoto);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(this);
        adapter.setOnClick(this);
        choiceDialog = new ChoiceDialog(this);
        choiceDialog.setOnClik(this);
        infoID = getIntent().getStringExtra("info_id");
    }

    private void initDialog() {
        dialog = new LoadingDialog(this);
        dialog.setText("正在提交");
    }

    @Override
    protected void responseData(GsonBaseProtocol mGsonBaseProtocal) {

    }

    @Override
    protected HttpLoader initHttpLoader() {
        return null;
    }

    @Override
    protected int initContentView() {
        return R.layout.dream_data_activity;
    }

    @Override
    public boolean onEventBus(BaseEventBean baseEventBean) {

        return false;
    }

    @OnClick({R.id.ll_choose_prove, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_prove:
                getBank();
                break;
            case R.id.btn_commit:
                commit();
                break;
        }
    }

    private void commit() {
        name = editName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showToast("请填写真实姓名");
            return;
        }
        id = editId.getText().toString().trim();
        if (TextUtils.isEmpty(id)) {
            ToastUtil.showToast("请填写身份证号码");
            return;
        }
        phone = editPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showToast("请填写手机号码");
            return;
        }
        if (bankType.equals("-1")) {
            ToastUtil.showToast("请选择开户银行");
            return;
        }
        bankNum = editCardId.getText().toString().trim();
        if (TextUtils.isEmpty(bankNum)) {
            ToastUtil.showToast("请填写银行卡号");
            return;
        }
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<File> listFile = ImageUtils.compressImages(listPhoto);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        releaseDream(listFile);
                    }
                });
            }
        }).start();
    }


    private void releaseDream(List<File> listFile) {
        UploadHttpLoader requestHttpLoader = new UploadHttpLoader(LaunchDreamProtocol.class);
        Map<String, String> map = new HashMap<>();
        map.put("user_id", MyApplication.getUserID());
        map.put("info_id", infoID);
        map.put("receive_name", name);
        map.put("receive_num", id);
        map.put("receive_tel", phone);
        map.put("bank_id", bankType);
        map.put("bank_card", bankNum);
        requestHttpLoader.setParams(NetConfig.SUPPLY_DREAM, listFile, map, "prove_img");
        requestHttpLoader.showDialog(this, true, "正在提交");
        requestHttpLoader.executor(new ResultListener<LaunchDreamProtocol>() {
            @Override
            public void success(LaunchDreamProtocol mGsonBaseProtocol) {
                FileUtils.clearImage();
                dialog.dismiss();
                EventBus.getDefault().post(new BaseEventBean<>(Constants.TYPE_2));
                finish();
            }

            @Override
            public void error(String mErrorProtocal) {
                FileUtils.clearImage();
                dialog.dismiss();
            }

            @Override
            public void notNet() {
                FileUtils.clearImage();
                dialog.dismiss();
            }

            @Override
            public void requestError() {
                FileUtils.clearImage();
                dialog.dismiss();
            }
        });
    }

    private void initHead() {
        headerview.setTitle("资料证明");
        headerview.bindOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case HeaderView.LEFT:
                        finish();
                        break;
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            getPermissions();
        } else {
            List<ImageInfo> imageInfo = new ArrayList<>();
            for (int i = 0; i < listPhoto.size(); i++) {
                ImageInfo info = new ImageInfo();
                info.bigImageUrl = listPhoto.get(i);
                info.thumbnailUrl = listPhoto.get(i);
                //拿到view的位置
                View imageView;
                imageView = gridview.getChildAt(position);
                info.imageViewWidth = imageView.getWidth();
                info.imageViewHeight = imageView.getHeight();
                int[] points = new int[2];
                imageView.getLocationInWindow(points);
                info.imageViewX = points[0];
                info.imageViewY = points[1] - getStatusBarHeight();
                imageInfo.add(info);
            }
            // 启动预览
            Intent intent = new Intent(this, ImagePreviewActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, (Serializable) imageInfo);
            bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, position - 1);
            intent.putExtras(bundle);
            startActivity(intent);
            overridePendingTransition(0, 0);
        }
    }

    @Override
    public void onItemClick(int position) {
        listPhoto.remove(position);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            // 获取返回的图片列表(存放的是图片路径)
            if (data != null) {
                //返回的图片路径
                listPhoto = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                adapter.setData(listPhoto);
            }
        }
    }

    //获取权限
    private void getPermissions() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean value) {
                        if (value) {//如果所有权限都通过
                            startCamra();
                        } else {
                            getPermissions();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void startCamra() {
        MultiImageSelector.create(this)
                .showCamera(true) // 是否显示相机. 默认为显示
                .count(8) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
//        .single() // 单选模式
                .multi() // 多选模式, 默认模式;
                .origin(listPhoto) // 默认已选择图片. 只有在选择模式为多选时有效
                .start(this, REQUEST_IMAGE);
    }


    private void getBank() {
        RequestHttpLoader requestHttpLoader = new RequestHttpLoader(BankTypeProtocol.class);
        Map<String, String> map = new HashMap<>();
        requestHttpLoader.setParams(NetConfig.BANK_TYPE, map);
        requestHttpLoader.showDialog(this, true);
        requestHttpLoader.executor(new ResultListener<BankTypeProtocol>() {
            @Override
            public void success(BankTypeProtocol mGsonBaseProtocol) {
                DreamDataActivity.this.bankTypeProtocol = mGsonBaseProtocol;
                List<ChoiceBean> list = new ArrayList<ChoiceBean>();
                for (BankTypeProtocol.DataBean bean : mGsonBaseProtocol.getData()) {
                    ChoiceBean choiceBean = new ChoiceBean();
                    choiceBean.name = bean.getBank_name();
                    list.add(choiceBean);
                }
                choiceDialog.setData(list);
                choiceDialog.show();
            }

            @Override
            public void error(String mErrorProtocal) {

            }

            @Override
            public void notNet() {

            }

            @Override
            public void requestError() {

            }
        });
    }

    @Override
    public void onClik(int position) {
        bankType = bankTypeProtocol.getData().get(position).getBank_id();
        txtBank.setText(bankTypeProtocol.getData().get(position).getBank_name());
    }
}
